package com.app.android.coliy.manager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.app.android.coliy.MyApplication;
import com.app.android.coliy.bean.UserInfo;
import com.app.android.coliy.constant.SPConstants;
import com.app.android.coliy.event.Event_Logout;
import com.app.android.coliy.tool.SPUtil;
import com.app.android.coliy.ui.activity.LoginActivity;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by Administrator on 2018/8/29.
 */

public class UserManager {

    private static UserInfo userInfo;

    public static void saveUserInfo(Context context) {
        SPUtil.putObjectValue(context, SPConstants.UserInfo, userInfo);
    }

    //保存用户信息
    public static void saveUserInfo(Context context, UserInfo info) {
        SPUtil.putObjectValue(context, SPConstants.UserInfo, info);
        userInfo = info;
    }

    //获取用户信息
    public static UserInfo getUserInfo(Context context) {
        if (userInfo == null) {
            userInfo = (UserInfo) SPUtil.getObjectValue(context, UserInfo.class, SPConstants.UserInfo);
        }
        if (userInfo == null) {
            userInfo = new UserInfo();
        }
        return userInfo;
    }

    //获取用户账号， 优先级： 手机号→ 邮箱
    public static String getUserNumber(Context context) {
        String number = "";
        UserInfo userInfo = getUserInfo(context);
        if (userInfo != null) {
            if (!TextUtils.isEmpty(userInfo.phoneNumber)) {
                number = userInfo.phoneNumber;
            } else if (!TextUtils.isEmpty(userInfo.emailAddress)) {
                number = userInfo.emailAddress;
            }
        }
        return number;
    }

    //保存Token
    public static void saveToken(Context context, String Token) {
        SPUtil.putValue(context, SPConstants.Token, Token);
    }

    //获取Token
    public static String getToken(Context context) {
        return SPUtil.getStringValue(context, SPConstants.Token, "");
    }

    //是否登录
    public static boolean isLogin(Context context) {
        return !TextUtils.isEmpty(getToken(context));
    }

    //退出登录
    public static void logout(Context context) {
        userInfo = null;
        saveUserInfo(MyApplication.context);
        saveToken(context, "");
        SPUtil.putValue(context, SPConstants.Cookie, "");
        EventBus.getDefault().post(new Event_Logout());
    }

    //跳登录页
    public static void showLogin(Activity context) {
        if (LoginActivity.isOpen == false) {
            LoginActivity.isOpen = true;
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            context.finish();
        }
    }

}
